package java19_5_9.com.huweilong.io;

import java.io.*;

/**
 * @author 是阿秋啊
 * @date 2022/05/09 21:03
 **/
public class CopyMkdir {
    static String source = "/Users/huweilong/Documents/IDEA/srcd";
    static String dest = "/Users/huweilong/Documents/IDEA/loca";
    public static void main(String[] args) throws IOException {
        File srcFile = new File(source);
        if (!srcFile.isDirectory()) {
            System.out.println("不是目录");
            return;
        }
        File destFile = new File(dest);
        if (destFile.exists()) {
            System.out.println("目录已存在");
            return;
        }
        destFile.mkdirs();
        traversal(srcFile,destFile);
    }

    private static void traversal(File srcFile, File destFile) throws IOException {
        File[] files = srcFile.listFiles();
        if (files == null) {
            return;
        }
        for (File file : files) {
            if (file.isDirectory()) {
                String srcPath = file.getCanonicalPath();
                String relative = srcPath.substring(source.length());
                String destPath = dest + relative;
                File file2 = new File(destPath);
                file2.mkdirs();
                traversal(file,destFile);
            }else if (file.isFile()) {
                String srcPath = file.getCanonicalPath();
                String relative = srcPath.substring(source.length());
                String destPath = dest + relative;
                try (InputStream is = new FileInputStream(srcPath)) {
                    try (OutputStream os = new FileOutputStream(destPath)) {
                        while (true) {
                            byte[] b = new byte[1024];
                            int n = is.read(b);
                            if (n == -1) {
                                break;
                            }
                            os.write(b, 0, n);
                        }
                        os.flush();
                    }
                }
            }
        }
    }
}
